import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

function increment() {
    console.log('->increment Action创建函数 - 返回Action');
    return { type: 'INCREMENT' };
}
function decrement() {
    console.log('->decrement Action创建函数 - 返回Action');
    return { type: 'DECREMENT' };
}
//如果你需要在action创建函数中返回函数，执行一些条件判断或者延迟操作，那么首先要安装Redux Thunk中间件：
function incrementIfOdd() {
    console.log('->incrementIfOdd Action创建函数 - 返回函数(通过Redux Thunk) 1');
    return (dispatch, getState) => {
        console.log('->incrementIfOdd Action创建函数 - 逻辑封装 2');
        const value = getState();
        if (value % 2 === 0) {
            return;
        }
        console.log('->incrementIfOdd Action创建函数 - dispatch Action 3');
        dispatch(increment());
    };
}
function incrementAsync(delay = 1000) {
    console.log('->incrementAsync Action创建函数 - 返回函数(通过Redux Thunk) 1');
    return dispatch => {
        console.log('->incrementAsync Action创建函数 - 逻辑封装 2');
        setTimeout(() => {
            console.log('->incrementAsync Action创建函数 - dispatch action 3');
            dispatch(increment());
        }, delay);
    };
}

function counter(state = 0, action) {
    console.log('->counter (reducer累加) 参数 state:', state , 'action:', action);
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        default:
            return state;
    }
}


console.log('=>createStore (创建Store, 使用thunk中间件)');
const store = createStore(counter, applyMiddleware(thunk));

console.log('=>store.getState() (获取当前状态)');
let currentValue = store.getState();
console.log('=>store.subscribe() (订阅. 触发时机,在reducer之后)');
store.subscribe(() => {
        const previousValue = currentValue;
        currentValue = store.getState();
        console.log('pre state:', previousValue, 'next state:', currentValue);
    }
);


console.log('=>store.dispatch(increment())');
store.dispatch(increment());

console.log('=>store.dispatch(incrementIfOdd())');
store.dispatch(incrementIfOdd());

console.log('=>store.dispatch(incrementAsync())');
store.dispatch(incrementAsync());

console.log('=>store.dispatch(decrement())');
store.dispatch(decrement());
